# Create your views here.
from rest_framework.views import APIView
from luffyapi.libs.geetest import GeetestLib
from rest_framework.response import Response
from django.conf import settings


class GeetestCaptchaAPIView(APIView):
    """极验验证码视图类"""
    def __init__(self):
        super().__init__()

        self.gt = GeetestLib(settings.GEETEST["pc_geetest_id"], settings.GEETEST["pc_geetest_key"])
        self.user_id = "test"
        self.status = False

    def get(self,request):
        """获取验证码"""
        self.status = self.gt.pre_process(self.user_id)
        # 将来可以使用redis来保存status和user_id
        response_str = self.gt.get_response_str()
        return Response(response_str)

    def post(self,request):
        """验证码二次验证"""
        challenge = request.data.get(self.gt.FN_CHALLENGE, '')
        validate = request.data.get(self.gt.FN_VALIDATE, '')
        seccode = request.data.get(self.gt.FN_SECCODE, '')
        if self.status:
            result = self.gt.success_validate(challenge, validate, seccode, self.user_id)
        else:
            result = self.gt.failback_validate(challenge, validate, seccode)
        result = {"status": "success"} if result else {"status": "fail"}
        return Response(result)


from rest_framework.generics import CreateAPIView
from .models import User
from .serializers import UserModelSerializer

class UserAPIView(CreateAPIView):
    """用户注册"""
    queryset = User.objects.all()
    serializer_class = UserModelSerializer


"""
接口访问地址： /user/mobile/(?P<mobile>1[3-9]\d{9})/
"""
from rest_framework import status

class MobileAPIView(APIView):
    def get(self,request,mobile):
        """验证手机号唯一性"""
        # 1、根据手机号到数据库里查找用户，返回结果
        try:
            User.objects.get(mobile=mobile)
            return Response({"status": False}, status=status.HTTP_400_BAD_REQUEST)
        except User.DoesNotExist:
            return Response({"status": True}, status=status.HTTP_200_OK)


from django_redis import get_redis_connection
from luffyapi.settings import constants
import random


class SMSAPIView(APIView):
    def get(self,request,mobile):
        from mycelery.mail.tasks import send_mail
        send_mail.delay(email="975531570@qq.com")
        """短信发送"""

        # 1. 判断手机号码是否在60秒内发送过短信
        redis_conn = get_redis_connection("sms_code")
        ret = redis_conn.get("send_%s" % mobile)
        if ret is not None:
            return Response({"message":"对不起，60秒内已经发送过短信，请耐心等待！"}, status=status.HTTP_400_BAD_REQUEST)

        # 2. 生成短信验证码
        sms_code = "%06d" % random.randint(1,999999)
        sms_time = constants.SMS_EXPIRE_TIME


        try:
            # 3.调用短信SDK，发送短信
            # 改用celery执行异步发送短信功能
            from mycelery.sms.tasks import send_sms
            send_sms.delay(mobile, sms_code, sms_time)

            # 3.1 保存短信验证码到redis[使用事务来处理多条命令]
            pipe = redis_conn.pipeline()  # 打开一个临时存放命令的管道对象
            pipe.multi()
            pipe.setex("sms_%s" % mobile, sms_time, sms_code)
            pipe.setex("send_%s" % mobile, constants.SMS_INTERVAL_TIME, "_")
            pipe.execute()

        except:
            return Response({"message": "短信发送失败！"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        # 5.响应发送短信的结果
        return Response({"message": "短信发送成功！"})




